<?php

namespace App\Http\Controllers\Admin\newWork;

use App\Http\Config\ErrorCode;
use App\Models\Admin\Configs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Excel;

class StatisticsController extends CommonController
{
    private $tableName = "new_work_list";
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    public function getDataStatistic(){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $workOrderCount = DB::table($this->tableName)->where("mall_id", request()->mallData['id'])->count(); // 总数
        $solveWorkOrderCount = DB::table($this->tableName)->where("status", "3")->where("mall_id", request()->mallData['id'])->count(); // 已解决
//        $pendingWorkOrderCount = DB::table($this->tableName)->where("status", "1")->where("mall_id", request()->mallData['id'])->count(); // 待处理
        $acceptWorkOrderCount = DB::table($this->tableName)->where("status", "2")->where("mall_id", request()->mallData['id'])->count(); // 处理中
        $newWorkOrderCount = DB::table($this->tableName)->where("create_time",'>',date('Y-m-d 00:00:00'))->where("mall_id", request()->mallData['id'])->count();
        $completeRate = $workOrderCount > 0 ? (sprintf("%.2f", $solveWorkOrderCount / $workOrderCount * 100)) : 0; // 完成率
        $this->returnData["data"] = [
            "totalOrderCount" => $workOrderCount, "solveOrderCount" => $solveWorkOrderCount, "acceptOrderCount" => $acceptWorkOrderCount,
            "newOrderCount" => $newWorkOrderCount, "completeRate" => $completeRate,
            "chartData" => [[
                "title" => "全部数据", "data" => [
                    ['name' => '已解决', 'value' => $solveWorkOrderCount],
                    ['name' => '处理中', 'value' => $acceptWorkOrderCount],
                    ['name' => '待处理', 'value' => $workOrderCount - $solveWorkOrderCount - $acceptWorkOrderCount]
                ], "list" => [
                    'feedbackCount' =>$workOrderCount,
                    'completeRate' => "{$completeRate}%"
                ]
            ]]
        ];
        $sevenTime = date('Y-m-d 00:00:00',strtotime('-7 day'));
        $fifteenTime = date('Y-m-d 00:00:00',strtotime('-15 day'));
        $thirtyTime = date('Y-m-d 00:00:00',strtotime('-30 day'));
        $this->returnData["data"]["chartData"][] = $this->getData($sevenTime, "7天数据");
        $this->returnData["data"]["chartData"][] = $this->getData($fifteenTime, "15天数据");
        $this->returnData["data"]["chartData"][] = $this->getData($thirtyTime, "30天数据");
        return $this->return_result($this->returnData);
    }

    public function getData($time, $title){
        $workOrderCount = DB::table($this->tableName)->where("create_time",'>',$time)->where("mall_id", request()->mallData['id'])->count(); // 总数
        $solveWorkOrderCount = DB::table($this->tableName)->where("status", "3")->where("create_time",'>',$time)->where("mall_id", request()->mallData['id'])->count(); // 已解决
        $acceptWorkOrderCount = DB::table($this->tableName)->where("status", "2")->where("create_time",'>',$time)->where("mall_id", request()->mallData['id'])->count(); // 处理中
        $completeRate = $workOrderCount > 0 ? (sprintf("%.2f", $solveWorkOrderCount / $workOrderCount * 100)) : 0; // 完成率
        $list = [
            "title" => $title, "data" => [
                ['name' => '已解决', 'value' => $solveWorkOrderCount],
                ['name' => '处理中', 'value' => $acceptWorkOrderCount],
                ['name' => '待处理', 'value' => $workOrderCount - $solveWorkOrderCount - $acceptWorkOrderCount]
            ]
        ];
        $list['list'] = [
            'feedbackCount' =>$workOrderCount,
            'completeRate' => "{$completeRate}%"
        ];
        return $list;
    }

    public function getChooseData(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (empty($request->startTime) || empty($request->endTime)) { // 默认是当月开始时间到今天
            list($y, $m, $d) = explode('-', date('Y-m-d'));
            $start = mktime(0, 0, 0, $m, 1, $y);
            $end = mktime(23, 59, 59, $m, $d, $y);
        }else {
            $startTime = date("Y-m-d", is_numeric($request->startTime) ? $request->startTime : strtotime($request->startTime));
            $endTime = date("Y-m-d", is_numeric($request->endTime) ? $request->endTime : strtotime($request->endTime));
            list($y, $m, $d) = explode('-', $startTime);
            $start = mktime(0, 0, 0, $m, $d, $y); // 开始时间戳
            list($y, $m, $d) = explode('-', $endTime);
            $end = mktime(23, 59, 59, $m, $d, $y); // 结束时间戳
        }
        $count = ceil(($end - $start) / 86400); // 总条数
        $page = isset($request->pageNo) ? $request->pageNo : 1;
        $pageSize = isset($request->pageSize) ? $request->pageSize : 10;
        $end = $end - (86400 * ($page - 1)*$pageSize); // 从第几页开始
        $i = 0; // 计数
        $orderList = [];
        do{
            $res = $this->getListByTime($end - 86399, $end); // 跟统计保持一致 ，  mktime(23, 59, 59, $m, $i, $y); 是今晚凌晨前1秒
            $res["time"] = date("Y-m-d", $end);
            $orderList[] = $res;
            $end = $end - 86400;
            if($i++ && $i >= $pageSize){
                break;
            }
        }while($end >= $start);
        if(!$orderList){
            $this->returnData['data'] = ['rows' => [], 'total' => 0];
        }else {
            $this->returnData['data'] = ['rows' => $orderList, 'total' => $count];
        }
        return $this->return_result($this->returnData);
    }

    // 统计订单时间范围内的数据
    public function getListByTime($start, $end)
    {
        $start = date("Y-m-d 00:00:00", $start);
        $end = date("Y-m-d 23:59:59", $end);
        $workOrderCount = DB::table($this->tableName)->whereBetween('create_time', [$start, $end])->where("mall_id", request()->mallData['id'])->count(); // 总数
        $solveWorkOrderCount = DB::table($this->tableName)->where("status", "3")->whereBetween('create_time', [$start, $end])->where("mall_id", request()->mallData['id'])->count(); // 已解决
        $acceptWorkOrderCount = DB::table($this->tableName)->where("status", "2")->whereBetween('create_time', [$start, $end])->where("mall_id", request()->mallData['id'])->count(); // 处理中
        $completeRate = $workOrderCount > 0 ? (sprintf("%.2f", $solveWorkOrderCount / $workOrderCount * 100)) : 0; // 完成率
        return [
            "totalOrderCount" => $workOrderCount,
            "pendingOrderCount" => $workOrderCount - $solveWorkOrderCount - $acceptWorkOrderCount,
            "acceptOrderCount" => $acceptWorkOrderCount,
            "solveOrderCount" => $solveWorkOrderCount,
            "completeRate" => "{$completeRate}%",
        ];
    }

    // 导出工单列表
    public function exportListData(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (empty($request->startTime) || empty($request->endTime)) { // 默认是当月开始时间到今天
            list($y, $m, $d) = explode('-', date('Y-m-d'));
            $start = mktime(0, 0, 0, $m, 1, $y);
            $end = mktime(23, 59, 59, $m, $d, $y);
        }else {
            $startTime = date("Y-m-d", is_numeric($request->startTime) ? $request->startTime : strtotime($request->startTime));
            $endTime = date("Y-m-d", is_numeric($request->endTime) ? $request->endTime : strtotime($request->endTime));
            list($y, $m, $d) = explode('-', $startTime);
            $start = mktime(0, 0, 0, $m, $d, $y); // 开始时间戳
            list($y, $m, $d) = explode('-', $endTime);
            $end = mktime(23, 59, 59, $m, $d, $y); // 结束时间戳
        }
        $orderList = [];
        do{
            $res = $this->getListByTime($end - 86399, $end); // 跟统计保持一致 ，  mktime(23, 59, 59, $m, $i, $y); 是今晚凌晨前1秒
            $res["time"] = date("Y-m-d", $end);
            $orderList[] = $res;
            $end = $end - 86400;
        }while($end >= $start);
        $arr[] = ['时间', '反馈总数', '待处理数', '处理中数', '已解决数', '完成率'];
        foreach ($orderList as $k => $v) {
            $arr[] = [
                $v['time'], $v['totalOrderCount'], $v['pendingOrderCount'], $v['acceptOrderCount'], $v['solveOrderCount'], $v['completeRate']
            ];
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if ($con->env == 'CLOUD') {
            $temp_file = tempnam(sys_get_temp_dir(), time() . ".xlsx");  //临时文件
            $a = Excel::create('日期统计-'.date("H:i:s"), function ($excel) use ($arr) {
                $excel->sheet('日期统计', function ($sheet) use ($arr) {
                    $sheet->rows($arr);
                });
            })->string('xlsx');
            file_put_contents($temp_file, $a);
            $data['code'] = 3;
            $data['name'] = '日期统计-'.date("H:i:s").'.xlsx';
            $data['data'] = $temp_file;
            return $data;
        } else {
            Excel::create('日期统计-'.date("H:i:s"), function ($excel) use ($arr) {
                $excel->sheet('日期统计', function ($sheet) use ($arr) {
                    $sheet->rows($arr);
                });
            })->export('xlsx');
        }
    }
}